package com.greatpengcode.controller;

import com.github.pagehelper.PageInfo;
import com.greatpengcode.pojo.Department;
import com.greatpengcode.pojo.Employee;
import com.greatpengcode.service.impl.DepartmentServiceImpl;
import com.greatpengcode.service.impl.EmployeeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeServiceImpl employeeService;
    @Autowired
    DepartmentServiceImpl departmentService;

    @RequestMapping("/emps")
    public String list(HttpServletRequest request, Model model){
        Integer pageNum = request.getParameter("pageNum") == null? 1 : Integer.valueOf(request.getParameter("pageNum"));

        PageInfo<Employee> pageInfo = employeeService.getAllEmployee(pageNum,5);
        model.addAttribute("employees",pageInfo.getList());
        model.addAttribute("pages",pageInfo.getPages());
        model.addAttribute("pageNum",pageInfo.getPageNum());
        model.addAttribute("pageSize",pageInfo.getPageSize());
        model.addAttribute("hasPreviousPage",pageInfo.isHasPreviousPage());
        model.addAttribute("hasNextPage",pageInfo.isHasNextPage());

//        Collection<Employee> employees = employeeService.getAllEmployee(1,2);
//        model.addAttribute("emps",employees);
        return "emp/list";
    }
    @GetMapping("/emp")
    public String toAddPage(Model model){
        Collection<Department> department = departmentService.getDepartments();
        model.addAttribute("departments",department);
        return "emp/add";
    }
    @PostMapping("/emp")
    public String addEmp(Employee employee){
        employee.setDepartment(departmentService.getDepartmentById(employee.getDepartment().getId()));
        employeeService.addEmployee(employee);
        return "redirect:/emps";
    }
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeService.getEmployeeById(id);
        model.addAttribute("emp",employee);
        Collection<Department> department = departmentService.getDepartments();
        model.addAttribute("departments",department);
        return "emp/update";
    }
    @RequestMapping("/updateEmp")
    public String updateEmp(Employee employee){
        System.out.println(employee);
        employeeService.updateEmployee(employee);
        return "redirect:/emps";
    }
    @RequestMapping("/delemp/{id}")
    public  String deleteEmp(@PathVariable("id") Integer id ){
        employeeService.deleteEmployee(id);
        return "redirect:/emps";
    }
}
